package com.mvc.loadconfig;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.mvc.util.Beans;

public class ParseXml implements Loadconfiginfor {
	@SuppressWarnings("unchecked")
	public Map<String, Beans> getConfigMap(String path) {
		Map<String, Beans> configmap = new HashMap<String, Beans>();
		SAXBuilder sab = new SAXBuilder();

		try {
			Document doc = sab.build(new File(path));
			Element root = doc.getRootElement();
			Element formsroot = root.getChild("forms");
			List<Element> forms = formsroot.getChildren();
			Map<String, String> formbean = new HashMap<String, String>();
			for (Element form : forms) {
				String formname = form.getAttributeValue("name");
				String formtype = form.getAttributeValue("type");
				formbean.put(formname, formtype);
			}
			Element actionroot = root.getChild("actions");
			List<Element> actions = actionroot.getChildren();
			for (Element action : actions) {
				String actionname = action.getAttributeValue("name");
				String actiontype = action.getAttributeValue("type");
				String actionpath = action.getAttributeValue("path");
				Beans xb = new Beans();
				xb.setActiontype(actiontype);
				xb.setName(actionname);
				xb.setPath(actionpath);
				xb.setFormtype(formbean.get(actionname));
				Map<String, String> result = new HashMap<String, String>();
				List<Element> results = action.getChildren();
				for (Element resultbean : results) {
					result.put(resultbean.getAttributeValue("name"),
							resultbean.getAttributeValue("path"));
				}
				xb.setResult(result);
				configmap.put(actionpath, xb);
			}
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return configmap;
	}
}
